package com.example.demo.read_write;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ClassName: ReadWriteLockDemoT
 * author: bob.ly
 * Version: 1.0.0
 * DateTime: 2021/08/01-00:28:00
 * Description:
 */
//资源类
class MyCache1 {
    //创建map集合
    private volatile Map<String, Object> map = new HashMap<>();

    //创建读写锁对象
    private ReadWriteLock rwLock = new ReentrantReadWriteLock();

    //放数据
    public synchronized void put(String key, Object value) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + " 正在写操作" + key);
        //暂停一会
        TimeUnit.SECONDS.sleep(1);
        //放数据
        map.put(key, value);
        System.out.println(Thread.currentThread().getName() + " 写完了" + key);
    }

    //取数据
    public synchronized Object get(String key) {
        Object result = null;
        System.out.println(Thread.currentThread().getName() + " 正在读取操作" + key);
        //暂停一会
        result = map.get(key);
        System.out.println(Thread.currentThread().getName() + " 取完了" + key);
        return result;
    }
}

public class ReadWriteLockDemoT {
    public static void main(String[] args) throws InterruptedException {
        MyCache1 myCache = new MyCache1();
        //创建线程放数据
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                try {
                    myCache.put(num + "", num + "");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
        System.out.println("=============");
        //创建线程取数据
        for (int i = 1; i <= 5; i++) {
            final int num = i;
            new Thread(() -> {
                myCache.get(num + "");
            }, String.valueOf(i)).start();
        }
    }
}
